﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using MasterDetailTemplate.Views;
using Xamarin.Forms;

namespace MasterDetailTemplate.Services.Implementations {
    /// <summary>
    /// 内容导航服务。（不能被测试，因为调用了view层的）
    /// By WZC
    /// </summary>
    public class ContentNavigationService : IContentNavigationService {
        /// <summary>
        /// MainPage。
        /// </summary>
        private MainPage _mainPage;

        /// <summary>
        /// MainPage。
        /// </summary>
        public MainPage MainPage =>
            _mainPage ?? (_mainPage = Application.Current.MainPage as MainPage);

        /// <summary>
        /// 内容页激活服务。
        /// </summary>
        private IContentPageActivationService _contentPageActivationService;

        /// <summary>
          /// 返回。
        /// </summary>
        public async Task GoBackAsync()
        {
            if (MainPage.Detail.Navigation.NavigationStack.Count > 1)
            {
                await MainPage.Detail.Navigation.PopAsync();
            }
        }

        /// <summary>
        /// 导航到页面。
        /// </summary>
        /// <param name="pageKey">页面键。</param>
        public async Task NavigateToAsync(string pageKey) =>
            await MainPage.Detail.Navigation.PushAsync(
                _contentPageActivationService.Activate(pageKey));

        /// <summary>
        /// 导航到页面。
        /// </summary>
        /// <param name="pageKey">页面键。</param>
        /// <param name="parameter">参数。</param>
        /// <returns></returns>
        public async Task NavigateToAsync(string pageKey, object parameter) {
            //1.取得目标页面
            var page = _contentPageActivationService.Activate(pageKey);
            //2.设置参数
            NavigationContext.SetParameter(page, parameter);
            //3.导航到page
            await MainPage.Detail.Navigation.PushAsync(page);
        }

        /// <summary>
        /// 内容导航服务。
        /// </summary>
        /// <param name="contentPageActivationService">内容页激活服务</param>
        public ContentNavigationService(
            IContentPageActivationService contentPageActivationService) {
            _contentPageActivationService = contentPageActivationService;
        }
    }
}